package com.haorui.lygyd.authority.filter;

import com.haorui.base.core.exception.BusinessException;
import com.haorui.base.core.utils.LoginUtil;
import com.haorui.base.system.entity.Account;
import com.haorui.base.system.entity.PermissionsEntity;
import com.haorui.base.system.enumerate.AccountType;
import com.haorui.base.system.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 陈刚
 * @version 1.0
 * @project ZNSM
 * @package com.haorui.authority.filter
 * @createDate 2017-12-30 3:18
 * @modfiyDate
 * @function
 */
@Component
public class RequestAuthorityFilter implements HandlerInterceptor {

    @Value("${jwt.authPath}")
    private String authPath;
    @Autowired
    AccountService accountService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        String url=httpServletRequest.getRequestURI();
        if(url.contains(authPath) ||  httpServletRequest.getMethod().equals(HttpMethod.OPTIONS.name())){
            return ;
            //这个filter毛用都没  还不删了
        }
        Account account= LoginUtil.getCurrentLoginAccount();
        if(account==null){
            httpServletResponse.sendError(401,"当前登陆用户无效！");
            return ;
        }
        if(account.getAccountType()!= AccountType.HOUTAIADMIN) {
            try {
                List<PermissionsEntity> permissionsEntityList = accountService.getPermissions(account.getId());
                boolean haspermiss = false;
                for (PermissionsEntity permissionsEntity : permissionsEntityList) {
                    if(permissionsEntity.getApi()==null){
                        continue;
                    }
                    if (url.contains(permissionsEntity.getApi())) {
                        haspermiss = true;
                        break;
                    }
                }
                if (!haspermiss) {
                    httpServletResponse.sendError(403, "无权限访问！");
                }

            } catch (BusinessException e) {
                httpServletResponse.sendError(403, e.getMessage());
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
